package dongze.com.ckdj.activity;

import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import dongze.com.ckdj.BR;
import dongze.com.ckdj.R;
import dongze.com.ckdj.adapter.ParkLotQueryAdapter;
import dongze.com.ckdj.data.entity.response.BrandResponse;
import dongze.com.ckdj.data.entity.response.GetVinMapResponse;
import dongze.com.ckdj.databinding.ActivityParkLotQueryBinding;
import dongze.com.ckdj.databinding.model.ParkingLotQueryModel;
import dongze.com.ckdj.databinding.model.VehicleNumberModel;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.util.MyLog;
import dongze.com.ckdj.util.Util;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/11/30.
 */

public class ParkLotQueryActivity extends ProgressableActivity {
    private static final String TAG = ParkLotQueryActivity.class.getSimpleName();
    ParkingLotQueryModel model;
    MapUtil mapUtil;
    List<BrandResponse> brands;
    ActivityParkLotQueryBinding binding;
    VehicleNumberModel mVehicleNumberModel = new VehicleNumberModel();
    private DisposableObserver mPendingDisposable;
    android.os.Handler mHandler;
    String mCurrentVehicleNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_park_lot_query);
        binding.setModel(new ParkingLotQueryModel(this));
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        model = binding.getModel();
        mVehicleNumberModel.addOnPropertyChangedCallback(mOnVehicleNumberChangedListener);
        mVehicleNumberModel.setOnItemClickListener(mOnVehicleNumberClick);
        binding.setInformationItemAutoCompleteTextModel(mVehicleNumberModel);
        mapUtil = new MapUtil(getAppCompenent());
        mHandler = new Handler(getMainLooper());
        loadBrands();
        model.brandPos.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                loadVoyage();
            }
        });
    }

    @Override
    protected void onDestroy() {
        mapUtil.dispose();
        super.onDestroy();
    }

    private void loadBrands() {
        mapUtil.getBrands("1",
                new DisposableObserver<List<BrandResponse>>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        doProcessing();
                    }

                    @Override
                    public void onNext(List<BrandResponse> value) {
                        String pref = Util.getPreference(ParkLotQueryActivity.this, Util.PREF_SELECTED_BRAND, null);
                        String[] entries = new String[value.size()];

                        for (int i = 0; i < value.size(); i++) {
                            entries[i] = value.get(i).getBrand_name();
                        }

                        model.brands.set(entries);
                        brands = value;

                        for (int i = 0; i < value.size(); i++) {
                            if (TextUtils.equals(value.get(i).getBrand_code(), pref))
                                model.brandPos.set(i);
                        }

                        loadVoyage();
                    }

                    @Override
                    public void onError(Throwable e) {
                        MyLog.e(TAG, "onError: ", e);
                        new AlertDialog.Builder(ParkLotQueryActivity.this)
                                .setMessage(e.getMessage())
                                .create()
                                .show();
                        finishProcessing();
                    }

                    @Override
                    public void onComplete() {
                        finishProcessing();
                    }
                });
    }

    private void loadVoyage() {
        if (brands.isEmpty() || brands.size() <= model.brandPos.get())
            return;

        mapUtil.getVoyage(brands.get(model.brandPos.get()).getBrand_code(), new DisposableObserver<List<String>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<String> value) {
                if (value.size() > 0) {
                    String[] arr = new String[value.size()];
                    value.toArray(arr);
                    String[] newArr = new String[arr.length + 1];
                    System.arraycopy(arr, 0, newArr, 1, arr.length);
                    newArr[0] = "";
                    model.voyage.set(newArr);
                    model.voyagePos.set(0);
                }
            }

            @Override
            public void onError(Throwable e) {
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    public void onQuery() {
//        if (TextUtils.equals(mVehicleNumberModel.getValue(), mCurrentVehicleNumber)) {
//            mVehicleNumberModel.setValue(null);
//            Toast.makeText(this, "车架号重复", Toast.LENGTH_SHORT).show();
//            return;
//        }

//        if (!TextUtils.isEmpty(mVehicleNumberModel.getValue())) {
            mCurrentVehicleNumber = mVehicleNumberModel.getValue();
//            一旦设置了hint并清空value，无法重置value，使用无vin查询
//            mVehicleNumberModel.setHint(mCurrentVehicleNumber);
//            mVehicleNumberModel.setValue(null);
//        }

        JsonObject jb = new JsonObject();
        jb.addProperty("bTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(model.from.get()));
        jb.addProperty("eTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(model.to.get()));
        jb.addProperty("vin", mVehicleNumberModel.getValue());
        jb.addProperty("voyage", model.voyage.get()[model.voyagePos.get()]);
        jb.addProperty("brand", model.brands.get()[model.brandPos.get()]);

        mapUtil.getVinMap(jb, new DisposableObserver<List<GetVinMapResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<GetVinMapResponse> value) {
                binding.recyclerview.setAdapter(new ParkLotQueryAdapter(value));
                model.count.set(String.valueOf(value.size()));
            }

            @Override
            public void onError(Throwable e) {
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    public void onReset() {

    }

    private Observable.OnPropertyChangedCallback mOnVehicleNumberChangedListener = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            if (propertyId == BR.value) {
                mHandler.removeCallbacks(mGetAutoCompleteDateRunnable);
                mHandler.postDelayed(mGetAutoCompleteDateRunnable, 300);
            }
        }
    };

    private Runnable mGetAutoCompleteDateRunnable = new Runnable() {
        @Override
        public void run() {
            MyLog.d(TAG, "run:mGetAutoCompleteDateRunnable");

            if (mVehicleNumberModel.getValue() == null
                    || mVehicleNumberModel.getValue().length() <= 3
                    || mVehicleNumberModel.getValue().equals(mCurrentVehicleNumber)
                    || model.brands.get() == null
                    || brands == null)
                return;

            if (mPendingDisposable != null && !mPendingDisposable.isDisposed()) {
                mPendingDisposable.dispose();
            }

            mPendingDisposable = new DisposableObserver<List<Pair<String, String>>>() {
                @Override
                protected void onStart() {
                    super.onStart();
//                    showProgressBar();
                    mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<查询中......>", null)));
                }

                @Override
                public void onNext(List<Pair<String, String>> value) {
                    MyLog.d(TAG, "onNext: mGetAutoCompleteDateRunnable");
                    mVehicleNumberModel.setEntries(value);
                    if (value.size() == 1) {
                        // 只有一个结果自动填充并开始做下一步查询
                        mVehicleNumberModel.setEntries(null);
                        mVehicleNumberModel.setValue(value.get(0).first);
                        onQuery();
                    } else if (value.size() == 0) {
                        mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<找不到车架号>", null)));
                    }
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<查询出错>", null)));
//                    hideProgressBar();
                }

                @Override
                public void onComplete() {
//                    hideProgressBar();
                }
            };

            mapUtil.mapInformationItemAutoCompleteTextModel(
                    mVehicleNumberModel.getValue(),
                    brands.get(model.brandPos.get()).getBrand_code(), model.voyage.get()[model.voyagePos.get()], mPendingDisposable);
        }
    };


    AdapterView.OnItemClickListener mOnVehicleNumberClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // start get detail info
            MyLog.d(TAG, "onItemClick: ");
            mHandler.removeCallbacks(mGetAutoCompleteDateRunnable);

            //check
            try {
                if (mVehicleNumberModel.getValue() == null
                        || !mVehicleNumberModel.getValue().equals(
                        mVehicleNumberModel.getEntries().get(position).first)
                        || (mVehicleNumberModel.getValue().startsWith("<") && mVehicleNumberModel.getValue().endsWith(">"))) {
                    MyLog.e(TAG, "onItemClick: check data consistency failed");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

            onQuery();
        }
    };
}
